package com.nd.service;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.dao.AdminMapper;
import com.nd.dao.PermissionMapper;
import com.nd.dao.RoleMapper;
import com.nd.pojo.bean.*;
import com.nd.pojo.bo.AdminAuthBO;
import com.nd.pojo.bo.AdminCreateBO;
import com.nd.pojo.vo.AdminAuthVO;
import com.nd.pojo.vo.AdministratorsOptionVO;
import com.nd.pojo.vo.CreateAdminVO;
import com.nd.pojo.vo.ErrorAndErrno;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: project2mall
 * @description: 管理员模块统一服务
 * @author: shit_code_builder
 * @create: 2021-06-04 20:50
 **/
@Service
public class AdministratorsService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Transactional(readOnly = true)
    public ErrorAndErrno<List<AdministratorsOptionVO.DataBean>> selectAdministratorsAll(){
        RoleExample roleExample = new RoleExample();

        List<Role> roles = roleMapper.selectByExample(roleExample);
        List<AdministratorsOptionVO.DataBean> data = new ArrayList<>();
        for (Role role : roles) {
            AdministratorsOptionVO.DataBean build = AdministratorsOptionVO.DataBean.builder().label(role.getName()).value(role.getId()).build();
            data.add(build);
        }
        AdministratorsOptionVO administratorsOptionVO = new AdministratorsOptionVO();
        administratorsOptionVO.setData(data);

        return administratorsOptionVO;
    }
    @Transactional(readOnly = true)
    public ErrorAndErrno adminListSelect(AdminAuthBO bo){
        AdminAuthVO adminAuthVO = new AdminAuthVO();
        PageHelper.startPage(bo.getPage(),bo.getLimit());

        AdminExample example = new AdminExample();
        example.setOrderByClause(bo.getSort() + " " + bo.getOrder());
        AdminExample.Criteria criteria = example.createCriteria();

        if (bo.getUsername()!=null||"".equals(bo.getUsername())) criteria.andUsernameLike("%" + bo.getUsername() + "%");
        criteria.andDeletedEqualTo(false);
        List<Admin> admins = adminMapper.selectByExample(example);

        AdminAuthVO.DataBean dataBean = new AdminAuthVO.DataBean();
        List<AdminAuthVO.ItemsBean> items = dataBean.getItems();
        for (Admin admin : admins) {
            AdminAuthVO.ItemsBean build = AdminAuthVO.ItemsBean.builder().avatar(admin.getAvatar()).id(admin.getId()).username(admin.getUsername()).roleIds(admin.getRoleIds()).build();
            items.add(build);
        }
        PageInfo<Admin> goodsPageInfo = new PageInfo<>(admins);
        long total = goodsPageInfo.getTotal();
        dataBean.setTotal(total);
        adminAuthVO.setData(dataBean);

        return adminAuthVO;
    }
    @Transactional(isolation = Isolation.DEFAULT)
    public ErrorAndErrno<CreateAdminVO.DataBean> createAdmin(AdminCreateBO bo) throws RuntimeException {
        DateTime now = DateTime.now();
        Integer integer = adminMapper.selectIdByName(bo.getUsername());

        if (integer!=null){
            boolean b = adminMapper.selectDeleteByName(bo.getUsername());
            if (!b) throw new RuntimeException("该用户已存在,无法注册");
            else { adminMapper.deleteByPrimaryKey(integer); }
        }
        String password=BCrypt.hashpw(bo.getPassword(),BCrypt.gensalt());
        Admin build = Admin.builder().username(bo.getUsername()).password(password).avatar(bo.getAvatar()).roleIds(bo.getRoleIds()).addTime(now).updateTime(now).deleted(false).build();
        int insert = adminMapper.insert(build);
        if (insert!=1)throw new RuntimeException("插入用户失败 ,请重试");
        Integer id = adminMapper.selectIdByName(bo.getUsername());
        String nowString = now.toString();
        CreateAdminVO.DataBean build1 = CreateAdminVO.DataBean.builder().addTime(nowString).updateTime(nowString).username(bo.getUsername()).password(password).roleIds(bo.getRoleIds()).avatar(bo.getAvatar()).id(id).build();
        CreateAdminVO createAdminVO = new CreateAdminVO();
        createAdminVO.setData(build1);
        return createAdminVO;
    }

    @Transactional(isolation = Isolation.DEFAULT)
    public ErrorAndErrno updateAdmin(AdminCreateBO bo) throws RuntimeException {
        Admin admin = adminMapper.selectByPrimaryKey(bo.getId());
        Integer integer = adminMapper.selectIdByName(bo.getUsername());
        if (integer!=null&& !admin.getId().equals(integer)){
            throw new RuntimeException("用户名已存在,更新失败");
        }else if(admin.getDeleted()){
            throw new RuntimeException("该用户不存在");
        }
        String password=BCrypt.hashpw(bo.getPassword(),BCrypt.gensalt());
        DateTime now = DateTime.now();
        admin.setUpdateTime(now);
        admin.setAvatar(bo.getAvatar());
        admin.setPassword(password);
        admin.setRoleIds(bo.getRoleIds());
        admin.setUsername(bo.getUsername());
        adminMapper.updateByPrimaryKey(admin);

        DateTime dateTime = new DateTime(admin.getAddTime());
        String addtime = dateTime.toString();
        String updatetime = now.toString();

        CreateAdminVO.DataBean build1 = CreateAdminVO.DataBean.builder().addTime(addtime).updateTime(updatetime).username(bo.getUsername()).password(password).roleIds(bo.getRoleIds()).avatar(bo.getAvatar()).id(bo.getId()).build();
        CreateAdminVO createAdminVO = new CreateAdminVO();
        createAdminVO.setData(build1);
        return createAdminVO;
    }

    public ErrorAndErrno deleteAdmin(AdminCreateBO bo) {
        Integer integer = adminMapper.selectIdByName(bo.getUsername());
        if (integer.equals(bo.getId())){
            Admin admin = new Admin();
            admin.setId(integer);
            admin.setDeleted(true);
            adminMapper.updateByPrimaryKeySelective(admin);
        }else {
            throw new RuntimeException("删除失败");
        }
    return new ErrorAndErrno();
    }
}
